<?php

App::uses('AppController', 'Controller');

class ActivitiesController  extends AppController {
	
	public $paginate = array(
		'limit' => ITEMS_PER_PAGE,
		'order' => array(
			'Activity.date'=>'desc'
		)
	);
	
	public $uses = array('Activity', 'Member', 'MemberChoirFunction');
	
	public function index() {
		$this->paginate = array(
			'page' => $page,
			'limit' => ITEMS_PER_PAGE
		);
		$this->set("data", $this->paginate('Activity'));
	}
	
	protected function _setCommonData() {
		$this->set("conductors", $this->MemberChoirFunction->find('all', array(
			'fields' => array('Member.id', 'Member.firstname', 'Member.surname', 'Function.name'),
			'conditions' => array(
				'function_id' => array(3,4,5,6)
			),
			'joins' => array( 
				array(
					'table' => 'members',
					'alias' => 'Member',
					'type' => 'INNER',
					'conditions' => array('Member.id = MemberChoirFunction.member_id')
				),
				array(
					'table' => 'functions',
					'alias' => 'Function',
					'type' => 'INNER',
					'conditions' => array('Function.id = MemberChoirFunction.function_id')
				)
			)
		)));
		
		$this->set("all_members", $this->Member->find("all", array("fields"=>array("Member.id", "Member.firstname", "Member.surname"))));
	}
	
	public function create() {
		$this->Activity->create();
		$this->set("data", $this->Activity->data);
		
		$this->_setCommonData();
		$this->render("form");
	}
	
	public function edit($id) {
		$this->set("data", $this->Activity->findById($id));
		$this->_setCommonData();
		$this->render("form");
	}
	
	public function save(){
		if($this->request->is('post')){
			$data = $this->data;
			unset($data['AllMembers']);
			
			$this->Activity->create($data);
			$this->Activity->set($data);
			if($this->Activity->validates()){
				// delete related members
				if($this->Activity->id > 0){
					$this->Activity->MembersActivity->deleteAll(array('activity_id'=>$this->Activity->id));
				}
				
				if($this->Activity->saveAll($data)){
					$this->setFlash(strtotitle(__('saved')) . ".", "ok");
					$this->redirect('/activities/edit/' . $this->Activity->id);
				}else{
					$this->setFlash(strtotitle(__('save failed')) . ". " . strtotitle(__('invalid data')) . ".");
					$this->set("data",$data);
					$this->_setCommonData();
					return $this->render('form');
				}
			}else{
				$this->setFlash(strtotitle(__('save failed')) . ". " . strtotitle(__('invalid data')) . ".");
				$this->set("data",$data);
				$this->_setCommonData();
				return $this->render('form');
			}
		}
		$this->redirect("/activities");
	}
	
}